<?php
/**
 * @copyright meila.com
 * @author shaopu@
 * @name 
 * @param 
 *         $xxx = 作用
 * @static 
 *         XXX = 作用
 * 
 * 
 */

class ml_tool_securecode
{
    const SECRET_KEY = '-Me!LA';
    /**
     * 生成安全码
     *
     * @return string
     */
    static function init_scode()
    {
        $time = time();
        $scode =  base_convert(md5($time.self::SECRET_KEY),16,36).base_convert($time , 10 , 36);
        return $scode;
    }
    /**
     * 验证安全码
     *
     * @param string $scode
     * @param int $time_limit    时间限制
     * @return bool
     */
    static function check_scode($scode , $time_limit = 600)
    {
        $time = base_convert(substr($scode , -6) , 36 , 10);
        if(time()-$time > $time_limit)
            return false;
        else if(base_convert(md5($time.self::SECRET_KEY),16,36) != substr($scode , 0 , 25))
            return false;
        return true;
    }
    
    /**
     * 获取加密字符串 含邮箱和时间信息
     * 在 注册邀请码 找回密码时用到
     *
     * @param string $txt
     * @return string
     */
    static function passport_encrypt($txt) {        
        $encrypt_key = md5(rand(0, 32000));
        $txt = $txt.self::SECRET_KEY.time();
        $ctr = 0;
        $tmp = '';
        for($i = 0;$i < strlen($txt); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
        }
        return base64_encode($tmp);
    }
    
    /**
     * 将邮件里的字符串解密获得邮箱和时间
     *
     * @param string $txt
     * @return array
     */
    
    static function passport_decrypt($txt) {
        $txt = base64_decode($txt);
        $tmp = '';
        for($i = 0;$i < strlen($txt); $i++) {
            $md5 = $txt[$i];
            $tmp .= $txt[++$i] ^ $md5;
        }
        
        $arrCode = explode(self::SECRET_KEY,$tmp);
        return $arrCode;
    }
    /**
     * 检查验证码是否相同
     *
     * @param string $user_input
     * @param string $session_code
     * @return bool
     */
    static function check_validate_code($user_input, $session_code)
    {
        if ($session_code == "")
        {
            return false;
        }
        if (trim($user_input) == trim($session_code))
        {
            return true;
        }
        $number = array(
        '0'     =>     '０',
        '1'     =>    '１',
        '2'        =>    '２',
        '3'        =>    '３',
        '4'        =>    '４',
        '5'        =>    '５',
        '6'        =>    '６',
        '7'        =>    '７',
        '8'        =>    '８',
        '9'        =>    '９',
        );
        $number_quan = '';
        for ($i = 0; $i < strlen($session_code); $i++)
        {
            $number_quan .= $number[$session_code[$i]];
        }
        if ($user_input == $number_quan)
        {
            return true;
        }
        return false;
    }
}
?>